import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tender_flutter/constant/app_config.dart';
import 'package:tender_flutter/constant/resource_path.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/home/api/api_home.dart';
import 'package:tender_flutter/page/home/model/company_investment_entity.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';

/// 分支机构
class CompanyMasterPage extends StatefulWidget {
  final String companyKey;
  final String companyName;

  const CompanyMasterPage({Key key, this.companyKey, this.companyName})
      : super(key: key);

  @override
  _CompanyMasterPageState createState() => _CompanyMasterPageState();
}

class _CompanyMasterPageState extends State<CompanyMasterPage> {
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  int page = AppConfig.page;

  /// 列表数据
  List<CompanyInvestmentEntity> _dataLists = [];

  Future _future;

  LoadState _loadState = LoadState.State_Loading;

  ///刷新数据
  Future _refresh() async {
    if (_refreshController.isRefresh) {
      page = 1;
    }
    if (_refreshController.isLoading) {
      page += 1;
    }
    setState(() {
      _future = _getList();
    });
  }

  /// 对外投资
  Future<ApiResponse<List<CompanyInvestmentEntity>>> _getList() async {
    return await ApiHome.companyMaster<List<CompanyInvestmentEntity>>(
        companyKey: widget.companyKey,
        companyName: widget.companyName,
        page: page);
  }

  /// 对外投资
  FutureBuilder<ApiResponse<List<CompanyInvestmentEntity>>>
      _buildFutureBuilder() {
    return FutureBuilder(
        future: _future,
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<List<CompanyInvestmentEntity>>>
                snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              List temps = snapshot.data.result;
              if (snapshot.data.status == Status.SUCCESS) {
                page == AppConfig.page
                    ? _dataLists = temps
                    : _dataLists += temps;
                if (_dataLists.isEmpty) {
                  _loadState = LoadState.State_Empty;
                } else {
                  _loadState = LoadState.State_Success;
                }
              } else {
                _loadState = LoadState.State_Error;
              }
            } else if (snapshot.hasError) {
              _loadState = LoadState.State_Error;
            }

            /// 结束刷新，处理分页
            if (_refreshController.isLoading) {
              _refreshController.loadComplete();
            }
            if (_refreshController.isRefresh) {
              _refreshController.refreshCompleted();
            }
          }

          return LoadStateLayout(
            bgColor: ThemeColors.colorWhite,
            state: _loadState,
            successWidget: _initList(),
          );
        });
  }

  @override
  void initState() {
    super.initState();
    _future = _getList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: ThemeColors.colorWhite,
        appBar: _initAppBar(),
        body: _buildFutureBuilder());
  }

  /// 导航
  Widget _initAppBar() {
    return BaseAppBar(context, Text("分支机构", style: FonStyle.navTextStyle()));
  }

  /// 列表
  Widget _initList() {
    return Padding(
        padding: EdgeInsets.symmetric(vertical: ScreenAdapter.height(20)),
        child: SmartRefresher(
            controller: _refreshController,
            enablePullUp: true,
            enablePullDown: true,
            onRefresh: _refresh,
            onLoading: _refresh,
            child: ListView.separated(
              itemCount: _dataLists.length,
              itemBuilder: (BuildContext context, int index) {
                CompanyInvestmentEntity model = _dataLists[index];
                return _getCell(data: model);
              },
              separatorBuilder: (BuildContext context, int index) {
                return Divider(
                  color: ThemeColors.colorType49,
                );
              },
            )));
  }

  /// 列表cell
  Widget _getCell({CompanyInvestmentEntity data}) {
    return Container(
      margin: EdgeInsets.only(
          left: ScreenAdapter.width(30),
          right: ScreenAdapter.width(30),
          bottom: ScreenAdapter.height(20)),
      padding: EdgeInsets.all(ScreenAdapter.width(30)),
      decoration: BoxDecoration(
          color: ThemeColors.colorWhite,
          border: Border.all(color: ThemeColors.colorType45, width: 0.5),
          borderRadius: BorderRadius.circular(ScreenAdapter.width(15))),
      child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(children: [
              Container(
                  margin:
                      EdgeInsets.symmetric(horizontal: ScreenAdapter.width(30)),
                  child: Image.asset(
                    RPath.imgPath + "icon_cm_code.png",
                    fit: BoxFit.scaleDown,
                  )),
              Expanded(
                  child: Text(
                data.companyCode,
                style: TextStyle(
                    color: ThemeColors.colorType1,
                    fontSize: ScreenAdapter.sp(30)),
                maxLines: 1,
              ))
            ]),
            SizedBox(height: ScreenAdapter.height(30)),
            Row(children: [
              Container(
                  margin:
                      EdgeInsets.symmetric(horizontal: ScreenAdapter.width(30)),
                  child: Image.asset(
                    RPath.imgPath + "icon_cm_name.png",
                    fit: BoxFit.scaleDown,
                  )),
              Expanded(
                  child: Text(
                data.companyName,
                style: TextStyle(
                    color: ThemeColors.colorType6,
                    fontSize: ScreenAdapter.sp(30)),
                maxLines: 1,
              ))
            ])
          ]),
    );
  }
}
